from datetime import datetime
from typing import Optional
from pydantic import BaseModel
from bson import ObjectId

class PyObjectId(ObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not ObjectId.is_valid(v):
            raise ValueError("Invalid objectid")
        return ObjectId(v)

    @classmethod
    def __modify_schema__(cls, field_schema):
        field_schema.update(type="string")

class MessageBase(BaseModel):
    chat_id: PyObjectId
    sender_id: PyObjectId
    content: str
    message_type: str  # 'text', 'image', 'voice'

class MessageCreate(MessageBase):
    pass

class MessageUpdate(BaseModel):
    content: Optional[str] = None
    is_read: Optional[bool] = None

class MessageInDBBase(MessageBase):
    id: PyObjectId
    created_at: datetime
    is_read: bool = False

    class Config:
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}

class Message(MessageInDBBase):
    pass

class MessageInDB(MessageInDBBase):
    pass